package com.jhz.speedy.component.service;

import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.jhz.speedy.common.base.IBaseService;
import com.jhz.speedy.component.control.Constants;
import com.jhz.speedy.logic.entity.DownLoadInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 版本服务
 * Created by JunHeZ on 2017/7/21.
 */
public class DownLoadService extends IBaseService {
    private static final String TAG = DownLoadService.class.getSimpleName();

    public static final String DOWNLOAD_INFO = "DownLoadInfo";  // 下载信息
    public static final String DOWNLOAD_EVENT = "download_event";  // 下载事件
    public static final int EVENT_DOWNLOAD_START = 0;    // 开始下载
    public static final int EVENT_DOWNLOAD_UPDATE = 1;    // 更新进度
    public static final int EVENT_DOWNLOAD_FINISH = 2;    // 下载完成
    public static final int EVENT_DOWNLOAD_ERROR = 3;    // 下载出错

    private DownLoadInfo downLoadInfo;  // 下载信息

    private Timer timerProgress;
    private TimerTask timerTaskProgress;    // 定时更新进度

    public static boolean isDownLoading = false;        // 是否正在下载

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return super.onBind(intent);
    }

    @Override
    protected DownLoadService getInstance() {
        return this;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent != null){
            downLoadInfo = (DownLoadInfo) intent.getSerializableExtra(DOWNLOAD_INFO);
            if(downLoadInfo != null){
                // 启动新线程下载软件
                new Thread(new DownloadRunnable()).start();
            }
        }
        return START_NOT_STICKY;
    }


    /**
     * 发送进度广播
     * @param event 进度事件
     */
    private void sendEventBroadcast(int event){
        Intent intent = new Intent(Constants.ACTION_DOWNLOAD_RECEIVER);
        intent.putExtra(DOWNLOAD_EVENT, event);
        intent.putExtra(DOWNLOAD_INFO, downLoadInfo);
        sendBroadcast(intent);
    }

    /**
     * 下载任务
     */
    private class DownloadRunnable implements Runnable {
        private InputStream dataInputStream;    // 网络数据输入流
        private FileOutputStream fileOutputStream;  // 文件输出流

        @Override
        public void run() {
            isDownLoading = true;   // 下载中

            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().get().url(downLoadInfo.downLoadUrl).build();
            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    dataInputStream = response.body().byteStream();  // 网络数据输入流

                    File apkFile = downLoadInfo.file;
                    fileOutputStream = new FileOutputStream(apkFile);   // 写到文件中

                    downLoadInfo.totalLength = response.body().contentLength();   // 获取内容总长度
                    downLoadInfo.downLength = 0;   // 已下载的长度
                    sendEventBroadcast(EVENT_DOWNLOAD_START);   // 开始下载
                    startProgressTimer();   // 启动进度定时器
                    Log.i(TAG, "开始下载apk totalLength = " + downLoadInfo.totalLength);

                    //定义缓冲区大小
                    byte[] bys = new byte[1024];
                    int len = -1;
                    while ((len = dataInputStream.read(bys)) != -1) {
                        fileOutputStream.write(bys, 0, len);
                        fileOutputStream.flush();
                        downLoadInfo.downLength += len;
                    }

                    // 下载完成
                    stopProgressTimer();    // 停止进度定时器
                    sendEventBroadcast(EVENT_DOWNLOAD_FINISH);
                }
            } catch (IOException e) {
                e.printStackTrace();
                stopProgressTimer();    // 停止进度定时器
                sendEventBroadcast(EVENT_DOWNLOAD_ERROR);

            } finally {
                //关闭io流
                if (dataInputStream != null) {
                    try {
                        dataInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    dataInputStream = null;
                }
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fileOutputStream = null;
                }
            }

            isDownLoading = false;  // 下载结束
        }
    }


    /**
     * 停止定时器
     */
    private void stopProgressTimer() {
        if (timerProgress != null) {
            timerProgress.cancel(); //关闭定时器
            timerTaskProgress.cancel();
        }
        timerProgress = null;
        timerTaskProgress = null;
    }

    /**
     * 初始化定时器
     */
    private void startProgressTimer() {
        stopProgressTimer();
        timerProgress = new Timer(); // 重建
        timerTaskProgress = new TimerTask() {
            public void run() {
                sendEventBroadcast(EVENT_DOWNLOAD_UPDATE);
            }
        };

        // 开启定时器，刷新通知栏
        timerProgress.schedule(timerTaskProgress, 10, 500); // 半秒一次定时器
    }


}
